import * as THREE from "three";
export module MyAtlas {
    class Rect {
        x: number = 0;
        y: number = 0;
        w: number = 0;
        h: number = 0;
    }
    export class Atlas {
        maps: { [id: string]: Rect } = {};
        tex: THREE.Texture;
        texwidth: number = 0;
        texheight: number = 0;
        loaded?: (at: Atlas) => void;
        constructor(loader: THREE.TextureLoader, urljson: string, urltex: string, callback?: (at: Atlas) => void) {
            this.tex = loader.load(urltex);
            this.loaded = callback;
            this.load(urljson);
        }
        async load(urljson: string): Promise<void> {

            let json = JSON.parse(await (await fetch(urljson)).text());
            this.texwidth = json["meta"]["size"]["w"];
            this.texheight = json["meta"]["size"]["h"];
            let frames = json["frames"];
            for (let key in frames) {
                let name = key;
                let dotpos = key.lastIndexOf(".");
                if (dotpos >= 0) {
                    name = key.substr(0, dotpos);
                }
                this.maps[name] = frames[key]["frame"] as Rect;
                console.log("name=" + key);
            }
            if (this.loaded)
                this.loaded(this);
        }
        CreatePlaneMesh(name: string,unit:number): THREE.Mesh {
            var rect = this.maps[name];
            var plane = new THREE.PlaneGeometry(rect.w/unit,rect.h/unit);
            var uv = plane.getAttribute("uv");
            var l = rect.x;
            var r = rect.x + rect.w;
            var t = this.texheight - rect.y;
            var b = this.texheight - rect.y - rect.h;
            uv.setXY(0, l / this.texwidth, t / this.texheight);//左上
            uv.setXY(1, r / this.texwidth, t / this.texheight);//右上
            uv.setXY(2, l / this.texwidth, b / this.texheight);//左下
            uv.setXY(3, r / this.texwidth, b / this.texheight);//右下
            let elem = new THREE.Mesh(plane, new THREE.MeshBasicMaterial(
                { map: this.tex, transparent: true }
            ));
            return elem;
        }
    }
}
